using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using System.IO;
using TestWeb.Models;
using TestWeb.Repositories;
using TestWeb.Helpers;

namespace TestWeb.Controllers
{	
	/// <summary>
	/// The partial of AdminController to manage TinTuc
	/// </summary>
	public partial class AdminController : BaseController
	{
		#region Methods

		/// <summary>
		/// The action for selecting range of elements in the table TinTuc 
		/// </summary>
		/// <param name="Page">The page which user want to go to</param>
		/// <returns>Result of an action method</returns>
		public ActionResult SelectTinTuc(int Page = 1)
		{
			var viewModel = new ViewModel
			{
				TinTucs = this.RepTinTuc.Select(Page)
			};
			this.UpdateModel(viewModel);
			
			ViewData["CurrentPage"] = Page;
			ViewData["TotalPage"] = this.RepTinTuc.TotalPages;
			
			return View("SelectTinTuc", viewModel);
		}

		/// <summary>
		/// The action for selecting range of elements based on foreign key in the table TinTuc 
		/// </summary>
		/// <param name="IDLoaiTinTuc">The foreign key of table which this table refer to</param>
		/// <param name="Page">The page which user want to go to</param>
		/// <returns>Result of an action method</returns>
		public ActionResult SelectTinTucByLoaiTinTuc(int IDLoaiTinTuc, int Page = 1)
		{
			var viewModel = new ViewModel
			{
				LoaiTinTucs = new List<LoaiTinTuc> { this.RepLoaiTinTuc.SelectByID(IDLoaiTinTuc) },
				TinTucs = this.RepTinTuc.SelectByLoaiTinTuc(IDLoaiTinTuc, Page)
			};
			this.UpdateModel(viewModel);

            ViewData["PartialRequest"] = "List";
			ViewData["CurrentPage"] = Page;
			ViewData["TotalPage"] = this.RepTinTuc.TotalPages;
			
			return View("SelectTinTuc", viewModel);
		}

		/// <summary>
		/// The action for selecting range of elements based on foreign key in the table TinTuc 
		/// </summary>
		/// <param name="IDNguoiDung">The foreign key of table which this table refer to</param>
		/// <param name="Page">The page which user want to go to</param>
		/// <returns>Result of an action method</returns>
		public ActionResult SelectTinTucByNguoiDung(Guid IDNguoiDung, int Page = 1)
		{
			var viewModel = new ViewModel
			{
				NguoiDungs = new List<NguoiDungModel> { this.RepNguoiDung.SelectByID(IDNguoiDung) },
				TinTucs = this.RepTinTuc.SelectByNguoiDung(IDNguoiDung, Page)
			};
			this.UpdateModel(viewModel);
			
			ViewData["CurrentPage"] = Page;
			ViewData["TotalPage"] = this.RepTinTuc.TotalPages;
			ViewData["IDNguoiDung"] = IDNguoiDung;
			
			return View("SelectTinTuc", viewModel);
		}

		/// <summary>
		/// The action for selecting a specified element in table TinTuc
		/// </summary>
		/// <param name="ID">The key for identifying the element will be deleted</param>
        /// <param name="CurrentPage">The current page which user went</param>
		/// <returns>Result of an action method</returns>
        public ActionResult DetailOfTinTuc(int ID, int CurrentPage)
		{
			var viewModel = new ViewModel
			{
				TinTucs = new List<TinTuc>() { this.RepTinTuc.SelectByID(ID) }
			};
			this.UpdateModel(viewModel);

            ViewData["CurrentPage"] = CurrentPage;

            return PartialView("Partials/Prt_TinTuc_Detail", viewModel.TinTucs.Count > 0 ? viewModel.TinTucs[0] : null);
		}

		/// <summary>
		/// The action to delete an element in table TinTuc without using Ajax
		/// </summary>
		/// <param name="ID">The key for identifying the element will be deleted</param>
		/// <returns>Result of an action method</returns>
		[AcceptVerbs(HttpVerbs.Delete)]
		public JsonResult DeleteTinTuc(int ID)
		{
			var msgTxt = string.Empty;
			var fileName = this.RepTinTuc.SelectByID(ID).HinhMinhHoa;
			var result = this.RepTinTuc.Delete(ID, ref msgTxt);
			
			if (result)
			{
				if (!this.DefaultImage.Equals(fileName))
					this.DeleteFile(Path.Combine(Server.MapPath(this.UploadImageDirectory), fileName));
			}
			
			return Json(new{
				Success = result,
                MsgTxt = result ? string.Format("The specified item with ID = {0} has been deleted", ID) : msgTxt,
				DeleteId = ID
			});
		}

		/// <summary>
		/// The action to delete an element in table TinTuc
		/// </summary>
		/// <param name="ID">The key for identifying the element will be deleted</param>
		/// <param name="CurrentPage">The current page</param>
		/// <returns>Result of an action method</returns>
		public ActionResult DeleteTinTucWithoutAjax(int ID, int CurrentPage = 1)
		{
			var msgTxt = string.Empty;
			var fileName = this.RepTinTuc.SelectByID(ID).HinhMinhHoa;
			var result = this.RepTinTuc.Delete(ID, ref msgTxt);
			
			if (result)
			{
				if (!this.DefaultImage.Equals(fileName))
					this.DeleteFile(Path.Combine(Server.MapPath(this.UploadImageDirectory), fileName));
			}
			
			var viewModel = new ViewModel
			{
				TinTucs = this.RepTinTuc.SelectToPage(CurrentPage)
			};
			this.UpdateModel(viewModel);
			
			ViewData["CurrentPage"] = CurrentPage;
			ViewData["TotalPage"] = this.RepTinTuc.TotalPages;
			ViewData["MsgTxt"] = result ? string.Format("The specified item with ID = {0} has been deleted", ID) : msgTxt;
			
			return View("SelectTinTuc", viewModel);
		}

		/// <summary>
		/// The action to update an element in table TinTuc 
		/// </summary>
		/// <param name="Forms">The collection parameters retrieved from Views</param>
		/// <returns>Result of an action method</returns>
		[ValidateInput(false)]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult UpdateTinTuc(FormCollection Forms)
		{
			var msgTxt = string.Empty;
			var CurrentPage = int.Parse(Forms.GetValues("CurrentPage")[0]);
			var iD = Forms.GetValues("ID")[0];
			var iDLoaiTinTuc = Forms.GetValues("IDLoaiTinTuc")[0];
			var iDNguoiDung = Forms.GetValues("IDNguoiDung")[0];
			var tieuDe = Forms.GetValues("TieuDe")[0];
			var noiDung = Forms.GetValues("NoiDung")[0];
			var file = Request.Files["HinhMinhHoa"];
			
			var item = this.RepTinTuc.SelectByID(int.Parse(iD));
			item.IDLoaiTinTuc = int.Parse(iDLoaiTinTuc);
			item.IDNguoiDung = Guid.Parse(iDNguoiDung);
			item.TieuDe = tieuDe;
			item.NoiDung = noiDung;
			
			var allowUpdate = true;
			var result = false;
			
			if (file.ContentLength != 0)
			{
				var fileName = string.Empty;
				if (UploadFile(file, this.UploadImageDirectory, ref fileName))
					item.HinhMinhHoa = fileName;
				else
				{
					allowUpdate = false;
					msgTxt = string.Format("Cannot upload image {0} to server", file.FileName);
				}
			}
			
			if (allowUpdate)
				result = this.RepTinTuc.Update(ref msgTxt);
			
			var viewModel = new ViewModel
			{
                LoaiTinTucs = new List<LoaiTinTuc> { this.RepLoaiTinTuc.SelectByID(item.IDLoaiTinTuc.Value) },
				TinTucs = this.RepTinTuc.SelectToPage(CurrentPage)
			};
			this.UpdateModel(viewModel);

            ViewData["PartialRequest"] = "List";
			ViewData["CurrentPage"] = CurrentPage;
			ViewData["TotalPage"] = this.RepTinTuc.TotalPages;
			ViewData["MsgTxt"] = result ? string.Format("The record with ID = {0} has been updated.", item.ID) : msgTxt;
      
			return View("SelectTinTuc", viewModel);
		}

		/// <summary>
		/// The action to insert an element in table TinTuc 
		/// </summary>
		/// <param name="Forms">The collection parameters retrieved from Views</param>
		/// <returns>Result of an action method</returns>
		[ValidateInput(false)]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult InsertTinTuc(FormCollection Forms)
		{
			var msgTxt = string.Empty;
			var CurrentPage = 1;
			var iDLoaiTinTuc = Forms.GetValues("IDLoaiTinTuc")[0];
			var iDNguoiDung = Forms.GetValues("IDNguoiDung")[0];
			var tieuDe = Forms.GetValues("TieuDe")[0];
			var noiDung = Forms.GetValues("NoiDung")[0];
			var file = Request.Files["HinhMinhHoa"];
			
			var item = new TinTuc
			{
				IDLoaiTinTuc = int.Parse(iDLoaiTinTuc),
				IDNguoiDung = Guid.Parse(iDNguoiDung),
				TieuDe = tieuDe,
				NoiDung = noiDung,
				HinhMinhHoa = this.DefaultImage
			};
			
			var result = this.RepTinTuc.Insert(item, ref msgTxt);
			if (result)
			{
				if (file.ContentLength != 0)
				{
					var fileName = string.Empty;
					if (this.UploadFile(file, this.UploadImageDirectory, ref fileName))
					{
						var addedItem = this.RepTinTuc.SelectByID(item.ID);
						addedItem.HinhMinhHoa = fileName;
						result = this.RepTinTuc.Update(ref msgTxt);
					}
				}
			}
			
			var viewModel = new ViewModel
			{
                LoaiTinTucs = new List<LoaiTinTuc> { this.RepLoaiTinTuc.SelectByID(int.Parse(iDLoaiTinTuc)) },
				TinTucs = this.RepTinTuc.SelectToPage(CurrentPage)
			};
			this.UpdateModel(viewModel);

            ViewData["PartialRequest"] = "Insert";
            ViewData["Result"] = result;
            ViewData["MsgTxt"] = result ? string.Format("The new record with ID = {0} has been added.", item.ID) : msgTxt.RemoveInvalidChars('\"', '\'', '\r', '\n');
			
			return View("SelectTinTuc", viewModel);
		}

		/// <summary>
		/// The action to navigate to the form for inserting new record
		/// </summary>
        /// <param name="IDLoaiTinTuc">The foreign key of table which this table refer to</param>
		/// <returns>Result of an action method</returns>
        public ActionResult EnterInsertTinTuc(int IDLoaiTinTuc)
		{
			var viewModel = new ViewModel
			{
                LoaiTinTucs = new List<LoaiTinTuc> { this.RepLoaiTinTuc.SelectByID(IDLoaiTinTuc) },
			};
			this.UpdateModel(viewModel);

            ViewData["PartialRequest"] = "Insert";

            return View("SelectTinTuc", viewModel);
		}

        /// <summary>
        /// The action to navigate to the form for deletting a range of records
        /// </summary>
        /// <param name="IDLoaiTinTuc">The foreign key of table which this table refer to</param>
        /// <param name="Page">The page which user want to go to</param>
        /// <returns>Result of an action method</returns>
        public ActionResult EnterDeleteRangeOfTinTuc(int IDLoaiTinTuc, int Page = 1)
        {
            var viewModel = new ViewModel
            {
                LoaiTinTucs = new List<LoaiTinTuc> { this.RepLoaiTinTuc.SelectByID(IDLoaiTinTuc) },
                TinTucs = this.RepTinTuc.Select(Page)
            };
            this.UpdateModel(viewModel);

            ViewData["PartialRequest"] = "Delete";
            ViewData["CurrentPage"] = Page;
            ViewData["TotalPage"] = this.RepLoaiTinTuc.TotalPages;
            return View("SelectTinTuc", viewModel);
        }

        /// <summary>
        /// The action to execute deleting one or multiple record in database 
        /// </summary>
        /// <param name="Forms"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteRangeOfTinTuc(FormCollection Forms)
        {
            var msgTxt = string.Empty;
            var result = false;
            var CurrentPage = 1;
            var numItemToBeDeleted = 0;
            var numItemDeleted = 0;

            var IDLoaiTinTuc = int.Parse(Forms.GetValues("IDLoaiTinTuc")[0]);
            var items = Forms.GetValues("MaTinTucs")[0];
            var itemsToDelete = items.Split(new char[] { ';' });

            foreach (string id in itemsToDelete)
            {
                if (!id.Equals(string.Empty))
                {
                    numItemToBeDeleted++;
                    var fileName = this.RepTinTuc.SelectByID(int.Parse(id)).HinhMinhHoa;
                    result = this.RepTinTuc.Delete(int.Parse(id), ref msgTxt);
                    if (result)
                    {
                        if (!this.DefaultImage.Equals(fileName))
                            this.DeleteFile(Path.Combine(Server.MapPath(this.UploadImageDirectory), fileName));
                        numItemDeleted++;
                    }   
                }
            }
            var viewModel = new ViewModel
            {
                LoaiTinTucs = new List<LoaiTinTuc> { this.RepLoaiTinTuc.SelectByID(IDLoaiTinTuc) },
                TinTucs = this.RepTinTuc.SelectToPage(CurrentPage)
            };
            this.UpdateModel(viewModel);

            // Get result 
            result = numItemToBeDeleted == numItemDeleted ? true : false;

            if (result)
                msgTxt = string.Format("All of the selected records (The number of records = {0}) have been deleted", numItemToBeDeleted);
            else
                msgTxt = string.Format("The number of records to be deleted = {0}, and the number of records have been deleted = {1}", numItemToBeDeleted, numItemDeleted);

            ViewData["PartialRequest"] = "Delete";
            ViewData["CurrentPage"] = CurrentPage;
            ViewData["TotalPage"] = this.RepTinTuc.TotalPages;
            ViewData["Result"] = result;
            ViewData["MsgTxt"] = msgTxt;

            return View("SelectTinTuc", viewModel);
        }

		#endregion

	}
}
